import React, { Component } from 'react';
import { connect } from 'dva';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Modal,
  Row,
  Col,
  Input,
  Select,
  Button,
  Table,
  Tooltip,
} from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { getAddressNameByCode } from '@/utils/utils';

const { Option } = Select;
const { Item } = Form;

const postSearch = {
  name: '',
  pageIndex: 1,
  pageSize: 5,
};

const gardenSearch = {
  pareaCode: '',
  name: '',
  type: 0,
  propertyId: '',
  pageIndex: 1,
  pageSize: 5,
};

interface SelectModalProps extends FormComponentProps {
  postInfo?: any;
  gardenInfo?: any;
  modalVisible: boolean;
  selectType: number;
  changeModal: (modalVisible: boolean, type: number, postInfo?: any) => void;
  fetchAction: (typeName: string, payload?: any) => void;
  INITINFO?: any;
}

interface SelectModalState {
  searchValues: any;
}

@connect(({
  boxManagementAdd: { postInfo, gardenInfo },
  common: { INITINFO },
}: any) => ({
  postInfo,
  gardenInfo,
  INITINFO,
}))

class SelectModalElem extends Component<SelectModalProps, SelectModalState> {
  state: SelectModalState = {
    searchValues: postSearch,
  };

  componentDidMount() {
    const { fetchAction, selectType } = this.props;
    this.setState({
      searchValues: selectType === 1 ? postSearch : gardenSearch,
    });
    fetchAction('fetchPost', postSearch);
    fetchAction('fetchGarden', gardenSearch);
    fetchAction('common/fetchGardenType');
    fetchAction('common/fetchAllProperty');
    fetchAction('common/fetchAreaList');
  }

  columns: any = () => {
    const {
      selectType,
    } = this.props;

    return selectType === 1
      ? [
        { title: 'ID', dataIndex: 'id' },
        {
          title: '名称',
          dataIndex: 'name',
          render: (text: string) => (
            <Tooltip title={text}>
              <div
                className="wordOmit"
                style={{ maxWidth: '150px' }}
              >{text}
              </div>
            </Tooltip>
          ),
        },
        { title: '经度', dataIndex: 'longitude' },
        { title: '纬度', dataIndex: 'latitude' },
        {
          title: '详细地址',
          dataIndex: 'address',
          render: (text: string) => (
            <Tooltip title={text}>
              <div className="wordOmit" style={{ maxWidth: '150px' }}>{text}</div>
            </Tooltip>
          ),
        },
        {
          title: '操作',
          render: (val: any, row: any) => (
            <span className="operLink" onClick={() => this.handleSelectPost(row)}>
              选择
            </span>
          ),
        },
      ]
      : [
        {
          title: '名称',
          dataIndex: 'name',
          render: (text: string) => (
            <Tooltip title={text}>
              <div
                className="wordOmit"
                style={{ maxWidth: '150px' }}
              >{text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '物业',
          dataIndex: 'propertyName',
          render: (text: string) => (
            <Tooltip title={text}>
              <div className="wordOmit" style={{ maxWidth: '150px' }}>{text}</div>
            </Tooltip>
          ),
        },
        {
          title: '地区',
          render: (val: any, row: any) => {
            const values = getAddressNameByCode({
              pareaCode: row.pareaCode,
              caredCode: row.careaCode,
              dareaCode: row.dareaCode,
            }).join('');

            return (
              <Tooltip title={values}>
                <div
                  className="wordOmit"
                  style={{ maxWidth: '150px' }}
                >{values}
                </div>
              </Tooltip>
            );
          },
        },
        { title: '经度', dataIndex: 'longitude' },
        { title: '纬度', dataIndex: 'latitude' },
        {
          title: '操作',
          render: (val: any, row: any) => (
            <span className="operLink" onClick={() => this.handleSelectGarden(row)}>
              选择
            </span>
          ),
        },
      ];
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const params = {
        ...values,
        pageIndex: 1,
        pageSize: 5,
      };
      this.setState({ searchValues: params }, () => {
        const { fetchAction, selectType } = this.props;
        fetchAction(selectType === 1 ? 'fetchPost' : 'fetchGarden', params);
      });
    });
  };

  handleSelectPost = ({ id, name }: any) => {
    const { changeModal } = this.props;
    changeModal(false, 1, { id, name });
  };

  handleSelectGarden = ({ id, name }: any) => {
    const { changeModal } = this.props;
    changeModal(false, 2, { id, name });
  };

  handleCancel = () => {
    const { selectType } = this.props;
    this.setState({ searchValues: selectType === 1 ? postSearch : gardenSearch }, () => {
      const { fetchAction } = this.props;
      fetchAction('fetchPost', postSearch);
      fetchAction('fetchGarden', gardenSearch);
    });

    const { changeModal } = this.props;
    changeModal(false, selectType);
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    this.setState({ searchValues: params }, () => {
      const { fetchAction, selectType } = this.props;
      fetchAction(selectType === 1 ? 'fetchPost' : 'fetchGarden', params);
    });
  };

  render() {
    const {
      searchValues: { pageIndex, pageSize },
    } = this.state;

    const {
      modalVisible,
      selectType,
      form: { getFieldDecorator },
      postInfo,
      gardenInfo,
      INITINFO: { gardenType, allPropertyList, areaList },
    } = this.props;

    const dataSource1 = postInfo ? postInfo.list : [];
    const dataSource2 = gardenInfo ? gardenInfo.list : [];
    const dataSource = selectType === 1 ? dataSource1 : dataSource2;

    const total1 = postInfo ? postInfo.count : 0;
    const total2 = gardenInfo ? gardenInfo.count : 0;
    const total = selectType === 1 ? total1 : total2;

    const pagination: object = {
      total,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['5', '10'],
      showTotal: () => `共${total}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Modal
        title={selectType === 1 ? '选择驿站' : '选择小区'}
        visible={modalVisible}
        width={800}
        destroyOnClose
        footer={null}
        onCancel={this.handleCancel}
      >
        <Form className="tableListForm marginB20" onSubmit={this.handleSearch}>
          {selectType === 1 && (
            <Row>
              <Col md={10} sm={24}>
                <Item label="驿站名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={4} sm={24} className="paddingL20">
                <Button
                  type="primary"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
              </Col>
            </Row>
          )}
          {selectType === 2 && (
            <div>
              <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                <Col md={8} sm={24}>
                  <Item label="选择省份" colon={false}>
                    {getFieldDecorator('pareaCode')(
                      <Select placeholder="请选择">
                        {areaList.map((item: any) => (
                          <Option value={item.code} key={item.id}>{item.name}</Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                </Col>
                <Col md={8} sm={24}>
                  <Item label="小区名称" colon={false}>
                    {getFieldDecorator('name')(
                      <Input allowClear placeholder="请输入" />,
                    )}
                  </Item>
                </Col>
                <Col md={8} sm={24}>
                  <Item label="物业公司" colon={false}>
                    {getFieldDecorator('propertyId')(
                      <Select
                        showSearch
                        placeholder="请选择"
                        filterOption={(input: any, option: any) => (
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        )}
                      >
                        {allPropertyList.map((item: any) => (
                          <Option value={item.id} key={item.id}>{item.name}</Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                </Col>
              </Row>
              <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                <Col md={8} sm={24}>
                  <Item label="　　类型" colon={false}>
                    {getFieldDecorator('type')(
                      <Select placeholder="请选择">
                        {gardenType.map((item: any) => (
                          <Option value={item.mCode} key={item.mCode}>{item.codeName}</Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                </Col>
                <Col md={8} sm={24} />
                <Col md={8} sm={24}>
                  <div className="flexFeView">
                    <Button
                      type="primary"
                      htmlType="submit"
                      className="smallButton"
                    >
                      查询
                    </Button>
                  </div>
                </Col>
              </Row>
            </div>
          )}
        </Form>

        <Table
          rowKey="id"
          className="statementTable"
          columns={this.columns()}
          scroll={{ x: '100%' }}
          dataSource={dataSource}
          pagination={pagination}
        />
      </Modal>
    );
  }
}

export default Form.create<SelectModalProps>()(SelectModalElem);
